package com.kanavi.batch.service;

import cn.hutool.core.util.IdUtil;
import com.kanavi.batch.entity.BatchOrder;
import com.kanavi.batch.entity.BatchOrderParam;
import com.kanavi.batch.entity.Request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@Service
public class JamesOrderService {


  @Autowired
  private RemoteServiceCall remoteServiceCall;

  LinkedBlockingDeque<Request> queue = new LinkedBlockingDeque<>();

  @PostConstruct
  public void init() {
    ScheduledExecutorService scheduled = new ScheduledThreadPoolExecutor(1);
    scheduled.scheduleAtFixedRate(() -> {
      //要做的事情
      int size = queue.size();
      if (size == 0) {
        return;
      }
      //here？  queue一定有数据
      List<Request> requestList = new ArrayList<>();
      for (int i = 0; i < size; i++) {
        Request request = queue.poll();
        requestList.add(request);
      }
      System.out.println("批量处理的数据量为:" + size);
      //拼接批量查询参数格式
      List<BatchOrderParam> params = new ArrayList<>();
      for (Request request : requestList) {
        BatchOrderParam param = new BatchOrderParam();
        param.setOrderCode(request.getOrderCode());
        param.setSerialNo(request.getSerialNo());
        params.add(param);
      }
      List<BatchOrder> responses = remoteServiceCall.queryOrderInfoByCodeBatch(params);
      Map<String, BatchOrder> responseMap = new HashMap<>(1);
      for (BatchOrder response : responses) {
        String serialNo = response.getSerialNo();
        //serialNo -----结果集 一对一
        responseMap.put(serialNo, response);
      }
      for (Request request : requestList) {
        BatchOrder result = responseMap.get(request.getSerialNo());
        request.getFuture().complete(result);
      }
    }, 0, 10, TimeUnit.MILLISECONDS);
  }

  /**
   * 1000个线程来调用 queryOrderInfo
   * @author tanghailan
   * @date 2021/5/21 0021 21:41
   * @param orderCode
   * @return com.kanavi.batch.entity.BatchOrder
   */
  public BatchOrder queryOrderInfo(String orderCode)
      throws ExecutionException, InterruptedException {
    //相当于纹身，能代表线程
    String serialNo = IdUtil.randomUUID();
    Request request = new Request();
    request.setSerialNo(serialNo);
    request.setOrderCode(orderCode);
    CompletableFuture<BatchOrder> future = new CompletableFuture<>();
    request.setFuture(future);
    queue.add(request);
    //调用远程接口
    return future.get();
  }
}
